//
//  OAuthViewController.swift
//  XMGWB
//
//  Created by 1 on 16/1/8.
//  Copyright © 2016年 xiaomage. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    
    // MARK:- 属性
    @IBOutlet weak var webView: UIWebView!
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadPage()
        
        // 初始化导航栏左右的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Done, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Done, target: self, action: "fill")
        
        webView.delegate = self
        
    }
    
    // MARK:- 自定义的函数
    private func loadPage() {
        // 1.获取url字符串
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        // 2.根据字符串创建URL
        guard let url = NSURL(string: urlStr) else {
            return
        }
        
        // 3.创建URLRequest对象
        let request = NSURLRequest(URL: url)
        
        // 4.用webView加载连接
        webView.loadRequest(request)
    }
    
    // MARK:- 事件监听
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fill() {
        // 1.写js代码
        let jsCode = "document.getElementById('userId').value='\(account)';document.getElementById('passwd').value='\(pwd)';"
        
        // 2.执行js
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
}

extension OAuthViewController:UIWebViewDelegate

{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
    
        
        //这里需要过滤非 code 的命令
        // 1.过滤非授权回调地址
        guard let urlStr = request.URL?.absoluteString where urlStr.hasPrefix(redirect_uri)
            else
        {
            return true
        }
        
        // 2.处理授权回调地址
        let code = "code="
        //where 的用处是判断是否有, code 这个值,有就赋值
        if let queryStr = request.URL?.query where queryStr.hasPrefix(code)
        {
            
            // 2.1截取code=后面的字符串
            let codeStr = queryStr.substringFromIndex(code.endIndex)
           
            loadAccessToken(codeStr)
            /*
            return true直接就进去了, 返回的参数如下
            */
            return true
            
        }
        // 3.关闭授权界面
        CBWLog("取消授权")
        close()
        return false
    }
   
    
    /// 根据已经授权的RequestToken换取AccessToken
    private func loadAccessToken(codeStr: String)
    {
        // 1.准备URL路径
        let path = "oauth2/access_token"
        // 2.准备参数
        let parameters = ["client_id": app_key, "client_secret": app_secret, "grant_type": "authorization_code", "code": codeStr, "redirect_uri": redirect_uri]
        // 3.利用AFN发送POST请求
        NetworkTools.shareInstance.POST(path, parameters: parameters, success: { (task, objc) -> Void in
            
            // 1.对服务器返回的数据进行安全校验
            // 注意: 在开发中, 但凡是服务器返回的数据/通过通知传递的数据...都需要进行安全校验
            guard let dict = objc as? [String: AnyObject] else
            {
                CBWLog("服务器没有返回数据")
                return
            }
            
            // 2.字典转模型
            let account = UserAccount(dict: dict)
            // CBWLog(account)
            
           
            // 4.获取用户信息
            account.loadUserInfo({ (dict, error) -> () in
                if error != nil
                {
                    CBWLog("获取用户信息失败")
                    return
                }
                // 3.将模型写入文件中
                account.saveUserAccount()
            })
          
            NSNotificationCenter.defaultCenter().postNotificationName(CBWChangeRootViewControllerNotification, object: self, userInfo: ["message": false])
            
            
            }) { (task, error) -> Void in
                CBWLog(error)
        }
        
    }
    
  
}
